package com.iseastar.guojiang.wallet;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

import com.iseastar.BaseActivity2;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.dialog.DialogMgr;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.shouhuobao.station.R;
import com.shouhuobao.station.wxapi.Constants;
import com.shouhuobao.take.weight.CircularImage;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import droid.frame.utils.GlideUtil;

/**
 * Created by joker on 2018/1/17.
 * 绑定微信界面
 */
public class CourierBindWXActivity extends BaseActivity2 implements View.OnClickListener {

    private TextView mUnBindWXTV;//未绑定微信界面
    private View mBindWXLayout;//绑定微信后的布局
    private CircularImage mWXHeadImageIV;//微信头像
    private TextView mWXNameTV;//微信昵称
    private TextView mBindOrUnBindTV;//绑定或解绑操作
    private TextView mWXTipsTV;//微信绑定或解绑须知

    private String unBindWXTipStr = "绑定须知：\n" +
            "绑定微信后，提现资金将被转入该微信零钱包";
    private String bindWXTipStr = "绑定须知：\n" +
            "1、解绑后才可以绑定新的微信账号；\n" +
            "2、更换微信后，提现资金将被转入该微信零钱包；\n" +
            "3、如果提现未成功之前更换微信，提现金额会被转入新更换的零钱包；\n" +
            "4、如果提现未成功之后解绑了微信账号，并未成功绑定，会造成提现失败。";
    private int isBindWX = 0;//1 已经绑定  0未绑定
    private String headerImageUrl = "";
    private String openId = "";
    private String nickName = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        openId = getIntent().getStringExtra("openId");
        if (isNotEmpty(openId)) {
            isBindWX = 1;
            nickName = getIntent().getStringExtra("name");
            headerImageUrl = getIntent().getStringExtra("headImageUrl");
            mUnBindWXTV.setVisibility(View.GONE);
            mBindWXLayout.setVisibility(View.VISIBLE);
            GlideUtil.loadImage(getContext(), headerImageUrl, 0, mWXHeadImageIV);
            mWXNameTV.setText(nickName);
            mBindOrUnBindTV.setText("解除绑定");
            mWXTipsTV.setText(bindWXTipStr);
        } else {
            isBindWX = 0;
            openId = "";
            headerImageUrl = "";
            nickName = "";
            mUnBindWXTV.setVisibility(View.VISIBLE);
            mBindWXLayout.setVisibility(View.GONE);
            mBindOrUnBindTV.setText("立即绑定");
            mWXTipsTV.setText(unBindWXTipStr);
        }
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.activity_courier_bind_wx);
        super.findViewById();
        getAppTitle().setCommonTitle("绑定微信");
        mUnBindWXTV = (TextView) findViewById(R.id.unbind_wx_tip_tv);
        mBindWXLayout = findViewById(R.id.bind_wx_ll);
        mWXHeadImageIV = (CircularImage) findViewById(R.id.wx_head_iv);
        mWXNameTV = (TextView) findViewById(R.id.wx_name_tv);
        mBindOrUnBindTV = (TextView) findViewById(R.id.wx_bind_or_unbind_tv);
        mWXTipsTV = (TextView) findViewById(R.id.wx_tip_tv);
        mBindOrUnBindTV.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //绑定或解绑微信
            case R.id.wx_bind_or_unbind_tv:
                if (isBindWX == 1) {//已经绑定，解除绑定
                    DialogMgr.showUnBindWXTips(getContext());
                } else {//进行绑定
                    IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
                    msgApi.registerApp(Constants.APP_ID);
                    final SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
                    req.state = "com.shouhuobao.station.courier";
                    msgApi.sendReq(req);
                }
                break;
        }
    }

    /**
     * 解除微信绑定
     */
    public void unBindWX() {
        showLoadingDialog(null);
        AppHttp.getInstance().deleteCourierWXAccout();
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            //微信登录获取accessToken值用于后期操作
            case MsgID.get_wx_login_token:
                final ReqResult<?> result = JSON.parser(msg.obj);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(result)) {
                            showLoadingDialog(null);
                            String jsonStr = result.getResult().toString();
                            try {
                                JSONObject jsonObject = new JSONObject(jsonStr);
                                String opneId = jsonObject.getString("openid").toString();
                                String access_token = jsonObject.getString("access_token").toString();
                                if (isNotEmpty(opneId) && isNotEmpty(access_token)) {
                                    AppHttp.getInstance().getUserMesg(access_token, opneId);
                                } else {
                                    cancelLoadingDialog();
                                    showToast("微信授权异常");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            cancelLoadingDialog();
                            showToast(result.getMessage());
                        }
                    }
                });
                return true;
            //微信登录获取微信用户信息
            case MsgID.get_wx_login_userinfo:
                String message = (String) msg.obj;
                try {
                    JSONObject object = new JSONObject(message);
                    openId = object.getString("openid").toString();
                    nickName = object.getString("nickname").toString();
                    headerImageUrl = object.getString("headimgurl").toString();
                    AppHttp.getInstance().bindCourierWXAccout(openId, nickName, headerImageUrl);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return true;
            //微信绑定回调
            case MsgID.courier_bind_wx_accout:
                cancelLoadingDialog();
                final ReqResult<?> bindWXResult = JSON.parser(msg.obj);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(bindWXResult)) {
                            isBindWX = 1;
                            mUnBindWXTV.setVisibility(View.GONE);
                            mBindWXLayout.setVisibility(View.VISIBLE);
                            showToast("绑定成功");
                            GlideUtil.loadImage(getContext(), headerImageUrl, 0, mWXHeadImageIV);
                            mWXNameTV.setText(nickName);
                            mBindOrUnBindTV.setText("解除绑定");
                            mWXTipsTV.setText(bindWXTipStr);
                            finish();
                        } else {
                            showToast(bindWXResult.getMessage());
                        }
                    }
                });
                return true;
            //微信解绑回调
            case MsgID.courier_delete_wx_accout:
                cancelLoadingDialog();
                final ReqResult<?> unBindWXResult = JSON.parser(msg.obj);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(unBindWXResult)) {
                            isBindWX = 0;
                            nickName = "";
                            openId = "";
                            headerImageUrl = "";
                            mUnBindWXTV.setVisibility(View.VISIBLE);
                            mBindWXLayout.setVisibility(View.GONE);
                            mBindOrUnBindTV.setText("立即绑定");
                            mWXTipsTV.setText(unBindWXTipStr);
                        } else {
                            showToast(unBindWXResult.getMessage());
                        }
                    }
                });
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    @Override
    public void finish() {
        Intent intent = new Intent();
        intent.putExtra("name", nickName);
        intent.putExtra("headImageUrl", headerImageUrl);
        intent.putExtra("openId", openId);
        setResult(Activity.RESULT_OK, intent);
        super.finish();
    }
}
